package approve.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import model.pojo.Employee;
import model.pojo.Languages;
import models.dao.AcEliManagerDao;
import models.dao.LangDAO;
import models.dao.LoginSystem;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class LoginActivity extends Activity{

	EditText username,pass,dbname;
	CheckBox rememberMeCbx;
	Button btLogin;
	TextView lbdbname,t,t2,tvwaiting;
	ImageView imageVN,imageEN,imageKR;
	LayoutInflater inflaterwaiting;
	View textEntryViewwaiting;
	AlertDialog.Builder builderwaiting;
	AlertDialog alertwaiting;
	int kt=0;
	public static int screenheight,screenwidth;
	String us="null",ps="null" ;
	private boolean read = true;
	AcEliManagerDao acelidao= new AcEliManagerDao();
	private final Handler uiHandler=new Handler();
	private boolean isUpdateRequired=false;
	public static Bundle alllangs = new Bundle();
	public static String database="null",typeLang = "EN";
	public static Employee emp=new Employee();
	public static Bundle lang;
	public static int soluong=0;
	public static boolean flagruntimer=true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.autologin);
		
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		screenheight = displaymetrics.heightPixels;
		screenwidth = displaymetrics.widthPixels;
		try{
			new Thread(){
				public void run() {
					
					readLanguageFile();
					getAlllangs();
					lang = alllangs.getBundle(typeLang);
					readFile();
					if(!us.equals("null") && !ps.equals("null") && !database.equals("null") ){
						if(acelidao.checkexitdb(database)==true){
							emp = checkLogin(us, ps);
							if (emp != null) {
								kt=1;
							} 
							else {
								kt=2;
							}
						}else{
							kt=3;
						}
					}
					
					uiHandler.post( new Runnable(){
						@Override
						public void run() {
							if(isUpdateRequired){
							}else{
								switch (kt) {
								case 1:
									startActivity();
									break;
								case 2:
									setContentView(R.layout.login);
									init();
									openDialogError();
									break;
								case 3:
									setContentView(R.layout.login);
									init();
									openDialogNoDB();
									break;
								default:
									setContentView(R.layout.login);
									kt=0;
									init();
									break;
								}
							}
						}
					} );
				}
			}.start();
		}catch (Exception e) {}
	}
	
	private void init(){
		lbdbname=(TextView) findViewById(R.id.lb_dbname);
		t = (TextView) findViewById(R.id.tendn);
		t2 = (TextView) findViewById(R.id.matkhau);
		btLogin = (Button) findViewById(R.id.btLogin);
		username = (EditText) findViewById(R.id.userName);
		pass = (EditText) findViewById(R.id.pass);
		dbname=(EditText)findViewById(R.id.tv_dbname);		
		rememberMeCbx = (CheckBox)findViewById(R.id.checkRemember);
		inflaterwaiting = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		textEntryViewwaiting = inflaterwaiting.inflate(R.layout.waiting, null);
		tvwaiting=(TextView)textEntryViewwaiting.findViewById(R.id.TextView01);					
		builderwaiting = new AlertDialog.Builder(LoginActivity.this);
		builderwaiting.setView(textEntryViewwaiting);
		builderwaiting.setCancelable(false);
		alertwaiting = builderwaiting.create();
		loadlable();
		LoginActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		imageVN = (ImageView)findViewById(R.id.imageViewVN);
		imageEN = (ImageView)findViewById(R.id.imageViewUK);
		imageKR = (ImageView)findViewById(R.id.imageViewKR);
		imageVN.setOnClickListener(processImageVN);
		imageEN.setOnClickListener(processImageEN);
		imageKR.setOnClickListener(processImageKR);
		username.setText("");
		pass.setText("");
		dbname.setText("");
		rememberMeCbx.setChecked(true);
		btLogin.setOnClickListener(loginbtn);
	}
	private OnClickListener loginbtn = new OnClickListener() {
		public void onClick(View v) {
//			btLogin.setBackgroundResource(R.drawable.bt_general_pressed);
			if(!username.getText().toString().equals("null") && !pass.getText().toString().equals("null") && !dbname.getText().toString().equals("null") && !username.getText().toString().equals("") && !pass.getText().toString().equals("") && !dbname.getText().toString().equals("")){
				alertwaiting.show();
				try{
					new Thread(){
						public void run() {

							if(acelidao.checkexitdb(dbname.getText().toString())==true){
								database=dbname.getText().toString();
								emp = checkLogin(username.getText().toString(), pass.getText().toString());
								if (emp != null) {
									if(rememberMeCbx.isChecked()==true){
										try{
											FileOutputStream file = openFileOutput("user.txt", Context.MODE_PRIVATE);
											file.write(database.getBytes());
											file.write("-".getBytes());
											file.write(emp.getUserName().getBytes());
											file.write("-".getBytes());
											file.write(pass.getText().toString().getBytes());
											file.close();
										}catch(Exception e){
											e.printStackTrace();
										}
										
									}else{
										try{
											FileOutputStream file = openFileOutput("user.txt", Context.MODE_PRIVATE);
											file.write("null".getBytes());
											file.write("-".getBytes());
											file.write("null".getBytes());
											file.write("-".getBytes());
											file.write("null".getBytes());
											file.close();
										}catch(Exception e){
											e.printStackTrace();
										}
									}
								} 
								else {
									kt=1;
								}
							}else{
								kt=2;
							}
							
							uiHandler.post( new Runnable(){
								@Override
								public void run() {
									if(isUpdateRequired){
									}else{
										switch (kt) {
										case 0:
											startActivity();
											alertwaiting.cancel();
											break;
										case 1:
											alertwaiting.cancel();
											openDialogError();
											break;
										case 2:
											alertwaiting.cancel();
											openDialogNoDB();
										default:
											break;
										}
									}
								}
							} );
						}
					}.start();
				}catch (Exception e) {}
				
			}
			
		}
	}; 

	private void startActivity() {
		Intent i = new Intent(this, MainEApproval.class);
		startActivity(i);
		finish();
	}
	private void openDialogError() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Warning");
		builder.setMessage(lang.getString("ac_tb_UserOrPassNotCorrect"));
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				kt=0;
			}
		});
		builder.show();
	}

	private void openDialogNoDB() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Warning");
		builder.setMessage(lang.getString("ac_CSDLKhongTonTai"));
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				kt=0;
			}
		});
		builder.show();
	}

	public Employee checkLogin(String username, String pass) {
		LoginSystem lg = new LoginSystem();
		Employee emp = lg.checkLogin(username, pass,database);
		return emp;
	}

	public void loadlable() {
		tvwaiting.setText(lang.getString("waiting")+"...");
		lbdbname.setText(lang.getString("ac_ma_DatabaseName"));
		t.setText(lang.getString("ac_ma_UserName"));
		t2.setText(lang.getString("ac_ma_Password"));
		btLogin.setText(lang.getString("ac_login"));
		rememberMeCbx.setText(lang.getString("rememberlogin"));
	}
	
	public Bundle getAlllangs() {
		if (isRead()) {
			LangDAO lang = new LangDAO();
			Bundle resultVN = new Bundle();
			Bundle resultEN = new Bundle();
			Bundle resultKR = new Bundle();
			try {
				ArrayList<Languages> arr = lang.allLang();
				for (int i = 0; i < arr.size(); i++) {
					resultVN.putString(arr.get(i).getId(), arr.get(i).getVn());
					resultEN.putString(arr.get(i).getId(), arr.get(i).getEn());
					resultKR.putString(arr.get(i).getId(), arr.get(i).getKr());
				};
			} catch (Exception E) {
				E.printStackTrace();
			}
			alllangs.putBundle("VN", resultVN);
			alllangs.putBundle("EN", resultEN);
			alllangs.putBundle("KR", resultKR);
		}
		setRead(false);
		return alllangs;
	}
	public boolean isRead() {
		return read;
	}
	public void setRead(boolean read) {
		this.read = read;
	}

	public OnClickListener processImageVN = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			typeLang = "VN";
			try{
				writeLanguageFile();
			}catch (Exception e) {
			}
			lang = alllangs.getBundle(typeLang);
			loadlable();
		}
	};

	public OnClickListener processImageEN = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			typeLang = "EN";
			try{
				writeLanguageFile();
			}catch (Exception e) {
			}
			lang = alllangs.getBundle(typeLang);
			loadlable();
		}
	};

	public OnClickListener processImageKR = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			typeLang = "KR";
			try{
				writeLanguageFile();
			}catch (Exception e) {
			}
			lang = alllangs.getBundle(typeLang);
			loadlable();
		}
	};

	private void readFile(){
		try {
			FileInputStream fr = openFileInput("user.txt");
			Scanner scanner = new Scanner(fr);
			scanner.useDelimiter("-");
			database=scanner.next().trim();
			us=scanner.next().trim();
			ps=scanner.next().trim();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void writeLanguageFile() throws Exception{
		FileOutputStream file = openFileOutput("language.txt", Context.MODE_PRIVATE);		
		file.write(typeLang.getBytes());
		file.close();
	}
	
	private void readLanguageFile(){		
		try {
			File fr = getBaseContext().getFileStreamPath("language.txt");
			if(fr.exists()){
				Scanner scanner = new Scanner(fr);
				typeLang=scanner.next().trim();
				if(typeLang.equals("")){
					typeLang="EN";
				}
			}else{
				typeLang="EN";
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(lang.getString("exitapp"));
		builder.setMessage(lang.getString("questionexitapp"));
		builder.setPositiveButton(lang.getString("ok"),new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				LoginActivity.this.moveTaskToBack(true);
				android.os.Process.killProcess(android.os.Process.myPid());
				android.os.Process.sendSignal(android.os.Process.myPid(), android.os.Process.SIGNAL_KILL);
			}
		});
		
		builder.setNegativeButton(lang.getString("cancel"), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}
}